﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using QT.IO;

namespace RouterReDial
{
    public partial class Form1 : Form
    {
        #region Attributes

        //private const int SmallWidth=410;
        private static int SmallHeight = 255;
        //private const int BigWidth = 410;
        private static int BigHeight = 450;
        int test = 0;

        private bool IsFull = false;
        private INIFile SettingFile = new INIFile(GlobalAttrib.iniPath);

        private Thread ReDialThread;
        private Thread GetIPThread;
        delegate void DeleGate(string txt, Color color);
        delegate void btnDeleGate(bool b);   

        #endregion

        #region Form

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SmallHeight = SystemInformation.CaptionHeight + SystemInformation.BorderSize.Height * 2 + SystemInformation.Border3DSize.Height * 2 + this.tabControl1.Location.Y + this.tabControl1.Height + this.statusStrip1.Height + 2; //+ this.groupBox1.Location.Y + this.statusStrip1.Height;
            test = SystemInformation.CaptionHeight + this.groupBox1.Location.Y + this.statusStrip1.Height;
            BigHeight = SystemInformation.CaptionHeight + SystemInformation.BorderSize.Height*2+ SystemInformation.Border3DSize.Height * 2 + this.groupBox1.Location.Y + this.groupBox1.Height + this.statusStrip1.Height + 2;

            GetIPThread = new Thread(new ThreadStart(GetIPRemote));
            ReDialThread = new Thread(new ThreadStart(ReDial));
            InitForm();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            if (ReDialThread.IsAlive && MessageBox.Show("正在进行拨号，是否强制退出？", "系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel)
            {
                return;
            }
            ReDialThread.Abort();
            e.Cancel = false;
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            GetIPThread.Start();
        }

        //初始化Form
        private void InitForm()
        {
            #region 窗口大小

            //this.Width = SmallWidth;
            this.Height = SmallHeight;

            #endregion

            #region 获取配置数据

            SettingFile.ReadInivalue("Config", "Policy", out GlobalAttrib.SelectedPolicy);
            SettingFile.ReadInivalue("Config", "IsAutoDial", out GlobalAttrib.IsAutoDial);
            SettingFile.ReadInivalue("Config", "AutoInterval", out GlobalAttrib.AutoDialInterval);
            GlobalAttrib.ReDialInterval = int.Parse(GlobalAttrib.AutoDialInterval);
            SettingFile.ReadInivalue("Config", "DialInterval", out GlobalAttrib.DialWaitTime);
            SettingFile.ReadInivalue("Config", "GetIPURL", out GlobalAttrib.GetIPURL);
            SettingFile.ReadInivalue("Config", "Regex", out GlobalAttrib.GetIPRegex);

            #endregion

            #region 获取路由器型号列表

            FileInfo[] Files = new DirectoryInfo(GlobalAttrib.policyPath).GetFiles();
            this.cbbRouterType.Items.Clear();
            foreach (FileInfo file in Files)
            {
                this.cbbRouterType.Items.Add(file.Name.Remove(file.Name.Length - 4));
            }

            #endregion

            #region 初始化配置信息

            this.cbbRouterType.SelectedIndex = 0;
            this.cbbRouterType.SelectedItem = GlobalAttrib.SelectedPolicy;
            if (GlobalAttrib.IsAutoDial == "1") this.cbReDial.Checked = true;
            else this.cbReDial.Checked = false;
            if (GlobalAttrib.AutoDialInterval == "") this.nudInterval.Value = GlobalAttrib.ReDialInterval;
            else this.nudInterval.Value = int.Parse(GlobalAttrib.AutoDialInterval);
            this.nudInterval.Enabled = false;
            if (GlobalAttrib.DialWaitTime == "") this.tbDialInterval.Text = GlobalAttrib.DialWaitTime;
            else this.tbDialInterval.Text = GlobalAttrib.DialWaitTime;

            #endregion

            #region 获取并初始化路由配置数据

            if (File.Exists(GlobalAttrib.policyPath + @"\" + GlobalAttrib.SelectedPolicy + @".ini"))
            {
                INIFile policyFile = new INIFile(GlobalAttrib.policyPath + @"\" + GlobalAttrib.SelectedPolicy + @".ini");
                policyFile.ReadInivalue("Config", "StatusURL", out GlobalAttrib.StatusUrl);
                policyFile.ReadInivalue("Config", "IPAddress", out GlobalAttrib.RouterAddress);
                policyFile.ReadInivalue("Config", "UserName", out GlobalAttrib.Username);
                policyFile.ReadInivalue("Config", "PassWord", out GlobalAttrib.Password);
                GlobalAttrib.Password = QT.Security.AESHelper.AESDecrypt(GlobalAttrib.Password);
                policyFile.ReadInivalue("Config", "Regex", out GlobalAttrib.Regex);

                this.tbRouterAdd.Text = GlobalAttrib.RouterAddress;
                this.tbUserName.Text = GlobalAttrib.Username;
                this.tbPassWord.Text = GlobalAttrib.Password;
            }
            ReadOnly(true);

            #endregion
        }

        //开启修改
        private void tbPage1_DoubleClick(object sender, EventArgs e)
        {
            ReadOnly(false);
        }

        #endregion

        #region Button

        private void btnSaveRouter_Click(object sender, EventArgs e)
        {
            if(SavePolicy()) MessageBox.Show("保存成功");
        }

        //进行拨号
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (GetIPThread.IsAlive)
            {
                try
                {
                    GetIPThread.Abort();
                }
                catch(ThreadAbortException)
                {
                }
            }

            if (!SaveSetting()) return;


            if(!SavePolicy()) return;

            INIFile policyFile = new INIFile(GlobalAttrib.policyPath + @"\" + GlobalAttrib.SelectedPolicy + @".ini");
                       
            policyFile.ReadInivalue("Config", "StatusURL", out GlobalAttrib.StatusUrl);
            policyFile.ReadInivalue("Config", "ConnUrl", out GlobalAttrib.ConnUrl);
            policyFile.ReadInivalue("Config", "DisConnUrl", out GlobalAttrib.DisConnUrl);

            this.rtbLogs.Clear();

            ReDialThread = new Thread(new ThreadStart(ReDial));
            ReDialThread.Start();
        }

        //取消拨号
        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (ReDialThread.IsAlive)
            {
                try
                {
                    ReDialThread.Abort();
                }
                catch (ThreadAbortException)
                {
                }
            }
            this.btnStart.Enabled = true;
            this.tsslReDialTime.Text = "";
        }

        //查看日志
        private void btnLogs_Click(object sender, EventArgs e)
        {
            if (IsFull)
            {
                //this.Width = SmallWidth;
                this.Height = SmallHeight;
                this.btnLogs.Text = "查看日志";
                IsFull = false;
            }
            else
            {
                //this.Width = BigWidth;
                this.Height = BigHeight;
                this.btnLogs.Text = "隐藏日志";
                IsFull = true;
            }
        }

        //保存配置信息
        private void btnSaveSetting_Click(object sender, EventArgs e)
        {
            if(SaveSetting()) MessageBox.Show("保存完成");
        }

        #endregion

        #region ComboBox

        //路由器类型切换事件
        private void cbbRouterType_SelectedIndexChanged(object sender, EventArgs e)
        {
            INIFile policyFile = new INIFile(GlobalAttrib.policyPath + @"\" + this.cbbRouterType.SelectedItem.ToString() + @".ini");

            policyFile.ReadInivalue("Config", "IPAddress", out GlobalAttrib.RouterAddress);
            policyFile.ReadInivalue("Config", "UserName", out GlobalAttrib.Username);
            policyFile.ReadInivalue("Config", "PassWord", out GlobalAttrib.Password);
            policyFile.ReadInivalue("Config", "Regex", out GlobalAttrib.Regex);

            this.tbRouterAdd.Text = GlobalAttrib.RouterAddress;
            this.tbUserName.Text = GlobalAttrib.Username;
            this.tbPassWord.Text = QT.Security.AESHelper.AESDecrypt(GlobalAttrib.Password);
        }

        #endregion

        #region CheckBox

        //选择自动拨号
        private void cbReDial_CheckedChanged(object sender, EventArgs e)
        {
            if (this.cbReDial.Checked == true) this.nudInterval.Enabled = true;
            else this.nudInterval.Enabled = false;
        }

        #endregion

        #region Save

        private bool SaveSetting()
        {
            if(!QT.Text.Match.IsPos(this.tbDialInterval.Text))
            {
                MessageBox.Show("断开后的等待时间必须为正整数");
                this.tabControl1.SelectedIndex = 1;
                this.tbDialInterval.Focus();
                return false;
            }

            try
            {
                SettingFile.WriteInivalue("Config", "IsAutoDial", this.cbReDial.Checked ? "1" : "0");
                GlobalAttrib.IsAutoDial = this.cbReDial.Checked ? "1" : "0";
                SettingFile.WriteInivalue("Config", "AutoInterval", this.nudInterval.Value.ToString());
                GlobalAttrib.AutoDialInterval = this.nudInterval.Value.ToString();
                SettingFile.WriteInivalue("Config", "DialInterval", this.tbDialInterval.Text);
                GlobalAttrib.DialWaitTime = this.tbDialInterval.Text;
            }
            catch (Exception)
            {
                MessageBox.Show("配置保存失败");
                return false;
            }

            return true;
        }

        private bool SavePolicy()
        {
            GlobalAttrib.SelectedPolicy = this.cbbRouterType.SelectedItem.ToString();
            Regex regex = new Regex(@"^http\:\/\/[0-2]{0,1}[0-9]{1,2}(\.[0-2]{0,1}[0-9]{1,2}){3}$");
            if (!regex.IsMatch(this.tbRouterAdd.Text))
            {
                MessageBox.Show("路由器地址错误，请按照格式“http://xxx.xxx.xxx.xxx”输入");
                return false;
            }

            try
            {
                INIFile policyFile = new INIFile(GlobalAttrib.policyPath + @"\" + GlobalAttrib.SelectedPolicy + @".ini");

                SettingFile.WriteInivalue("Config", "Policy", this.cbbRouterType.SelectedItem.ToString());
                policyFile.WriteInivalue("Config", "IPAddress", this.tbRouterAdd.Text);
                GlobalAttrib.RouterAddress = this.tbRouterAdd.Text;
                policyFile.WriteInivalue("Config", "UserName", this.tbUserName.Text);
                GlobalAttrib.Username = this.tbUserName.Text;
                if (this.tbPassWord.Text.Length > 0)
                {
                    policyFile.WriteInivalue("Config", "PassWord", QT.Security.AESHelper.AESEncrypt(this.tbPassWord.Text));
                    GlobalAttrib.Password = this.tbPassWord.Text;
                }
            }
            catch (Exception)
            {
                MessageBox.Show("路由信息保存失败");
                return false;
            }

            ReadOnly(true);
            return true;
        }

        #endregion

        #region Modify

        private void ReadOnly(bool b)
        {
            this.tbRouterAdd.ReadOnly = b;
            this.tbUserName.ReadOnly = b;
            this.tbPassWord.ReadOnly = b;
        }

        #endregion

        #region Thread&DeleGate

        //路由器拨号
        private void ReDial()
        {
            this.btnStart.Invoke(new btnDeleGate(setButton), new object[] { false });
            bool b;

            if (!GetCookie(GlobalAttrib.RouterAddress, GlobalAttrib.Username, GlobalAttrib.Password))
            {
                this.btnStart.Invoke(new btnDeleGate(setButton), new object[] { true }); this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "[" + DateTime.Now + "]", Color.Green });
                this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "System Error\n", Color.Black });
                return;
            }

            //获取当前IP
            GlobalAttrib.NewIP = GetIP(GlobalAttrib.RouterAddress + GlobalAttrib.StatusUrl, GlobalAttrib.RouterAddress, GlobalAttrib.authorizationStr, GlobalAttrib.Username, GlobalAttrib.Password, GlobalAttrib.Regex,out b);
            if (!b)
            {
                this.btnStart.Invoke(new btnDeleGate(setButton), new object[] { true }); this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "[" + DateTime.Now + "]", Color.Green });
                this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "System Error\n", Color.Black });
                return;
            }
            this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "[" + DateTime.Now + "]", Color.Green });
            this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "当前IP：" + GlobalAttrib.NewIP + "\n", Color.Black });

            bool ReDial = true;
            bool IsAutoDial = false;

            if (GlobalAttrib.IsAutoDial == "1") IsAutoDial = true;

            while (ReDial || IsAutoDial)
            {
                GlobalAttrib.PreviewIP = GlobalAttrib.NewIP;
                try
                {
                    this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "[" + DateTime.Now + "]", Color.Green });
                    this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "正在断开网络……\n", Color.Black });
                    if (ProcessCmd(GlobalAttrib.RouterAddress + GlobalAttrib.DisConnUrl, GlobalAttrib.RouterAddress + GlobalAttrib.StatusUrl, GlobalAttrib.authorizationStr, GlobalAttrib.Username, GlobalAttrib.Password))
                    {
                        this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "[" + DateTime.Now + "]", Color.Green });
                        this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "网络断开已完成\n", Color.Black });
                    }

                    this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "[" + DateTime.Now + "]", Color.Green });
                    for (int i = int.Parse(GlobalAttrib.DialWaitTime); i >= 0; i--)
                    {
                        this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { i + " ", Color.Black });
                        Thread.Sleep(1000);
                    }
                    this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "\n", Color.Black });

                    this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "[" + DateTime.Now + "]", Color.Green });
                    this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "正在进行重拨……\n", Color.Black });
                    if (ProcessCmd(GlobalAttrib.RouterAddress + GlobalAttrib.ConnUrl, GlobalAttrib.RouterAddress + GlobalAttrib.StatusUrl, GlobalAttrib.authorizationStr, GlobalAttrib.Username, GlobalAttrib.Password))
                    {
                        this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "[" + DateTime.Now + "]", Color.Green });
                        this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "网络重拨已完成\n", Color.Black });
                    }

                    this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "[" + DateTime.Now + "]", Color.Green });
                    this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "正在获取新IP，请稍后……\n", Color.Black });
                    Thread.Sleep(10000);
                    GlobalAttrib.NewIP = GetIP(GlobalAttrib.RouterAddress + GlobalAttrib.StatusUrl, GlobalAttrib.RouterAddress, GlobalAttrib.authorizationStr, GlobalAttrib.Username, GlobalAttrib.Password, GlobalAttrib.Regex, out b);
                    if (!b)
                    {
                        this.btnStart.Invoke(new btnDeleGate(setButton), new object[] { true }); this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "[" + DateTime.Now + "]", Color.Green });
                        this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "System Error\n", Color.Black });
                        return;
                    }
                    if (GlobalAttrib.NewIP != "0.0.0.0" && GlobalAttrib.NewIP != GlobalAttrib.PreviewIP)
                    {
                        this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "[" + DateTime.Now + "]", Color.Green });
                        this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "当前IP：" + GlobalAttrib.NewIP + "\n", Color.Black });
                        ReDial = false;
                    }
                    else if (GlobalAttrib.NewIP == "0.0.0.0")
                    {
                        this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "[" + DateTime.Now + "]", Color.Green });
                        this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "IP获取异常，程序将重新拨号\n", Color.Black });
                    }
                    else
                    {
                        this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "[" + DateTime.Now + "]", Color.Green });
                        this.rtbLogs.Invoke(new DeleGate(outTxt), new object[] { "获取到的IP和之前一样，程序将重新拨号\n", Color.Black });
                    }

                    if (!ReDial && IsAutoDial)
                    {
                        for (int i = GlobalAttrib.ReDialInterval * 60; i >= 0; i--)
                        {
                            int hour = i / 3600;
                            int min = i % 3600 / 60;
                            int sec = i % 3600 % 60;
                            this.tsslReDialTime.Text = "拨号将于 ";
                            this.tsslReDialTime.Text += hour.ToString();
                            this.tsslReDialTime.Text += ":";
                            this.tsslReDialTime.Text += min.ToString().Length == 1 ? "0" + min.ToString() : min.ToString();
                            this.tsslReDialTime.Text += ":";
                            this.tsslReDialTime.Text += sec.ToString().Length == 1 ? "0" + sec.ToString() : sec.ToString();
                            this.tsslReDialTime.Text += " 后开始";
                            Thread.Sleep(1000);
                        }
                    }
                }
                catch (ThreadAbortException)
                {
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

            this.btnStart.Invoke(new btnDeleGate(setButton), new object[] { true }); 
        }

        //通过远程地址获取IP
        private void GetIPRemote()
        {
            GlobalAttrib.NewIP = GetIP(GlobalAttrib.GetIPURL);
            outTxt("[" + DateTime.Now.ToString() + "]", Color.Green);
            outTxt("当前IP：" + GlobalAttrib.NewIP + "\n", Color.Black);
        }

        //Delegate 输入字符串到rtbLogs
        private void outTxt(string text,Color color)
        {
            if (this.rtbLogs.TextLength + text.Length > this.rtbLogs.MaxLength)
            {
                this.rtbLogs.Clear();
            }

            this.rtbLogs.SelectionColor = color; //System.Drawing.Color.Green;
            this.rtbLogs.AppendText(text);
            this.rtbLogs.SelectionColor = Color.Black;
            this.rtbLogs.ScrollToCaret();
        }

        //Delegate 设置开始按钮状态
        private void setButton(bool b)
        {
            this.btnStart.Enabled = b;
        }

        #endregion

        #region HttpWebRequest

        //获取Cookie
        private bool GetCookie(string LoginURL, string username, string password)
        {
            try
            {
                HttpWebRequest LoginWebRequest = (HttpWebRequest)HttpWebRequest.Create(LoginURL);
                LoginWebRequest.Method = "GET";
                LoginWebRequest.Credentials = new NetworkCredential(username, password);
                HttpWebResponse LoginWebResponse = (HttpWebResponse)LoginWebRequest.GetResponse();
                GlobalAttrib.authorizationStr = LoginWebRequest.Headers.Get("Authorization");
                LoginWebResponse.Close();
            }
            catch (ThreadAbortException)
            {
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    MessageBox.Show(ex.Message+"\n请检查用户名密码");
                    return false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            return true;
        }

        //获取页面返回内容
        private string GetHtml(string url, string ref_url, string authorizationStr, string username, string password)
        {
            string outHtmlData = "";
            try
            {
                HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                httpWebRequest.Referer = ref_url;
                httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                httpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
                httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727,; .NET CLR 3.0.04506,; .NET CLR 3.5.21022)";
                httpWebRequest.Method = "GET";
                if (string.IsNullOrEmpty(authorizationStr))
                {
                    httpWebRequest.Credentials = new NetworkCredential(username, password);
                }
                else
                {
                    httpWebRequest.Headers.Add("Authorization", authorizationStr);
                }
                HttpWebResponse webResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                if (webResponse.StatusCode == HttpStatusCode.OK)
                {
                    StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.Default);
                    outHtmlData = sr.ReadToEnd();
                    sr.Close();
                }
                else
                {
                    outHtmlData = "";
                }
                webResponse.Close();
            }
            catch (ThreadAbortException)
            {
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    MessageBox.Show(ex.Message + "\n请检查用户名密码");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return outHtmlData;
        }

        //执行带参页面，返回成功状态
        private bool ProcessCmd(string url, string ref_url, string authorizationStr, string username, string password)
        {
            bool ProcessStatus = false;
            try
            {
                HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                httpWebRequest.Referer = ref_url;
                httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                httpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
                httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727,; .NET CLR 3.0.04506,; .NET CLR 3.5.21022)";
                httpWebRequest.Method = "GET";
                if (string.IsNullOrEmpty(authorizationStr))
                {
                    httpWebRequest.Credentials = new NetworkCredential(username, password);
                }
                else
                {
                    httpWebRequest.Headers.Add("Authorization", authorizationStr);
                }
                HttpWebResponse webResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                if (webResponse.StatusCode == HttpStatusCode.OK) ProcessStatus=true;
                else ProcessStatus=false;
                webResponse.Close();
            }
            catch (ThreadAbortException)
            {
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    MessageBox.Show(ex.Message + "\n请检查用户名密码");
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
                ProcessStatus = false;
            }

            return ProcessStatus;
        }

        //通过页面返回内容采集IP
        private string GetIP(string url, string ref_url, string authorizationStr, string username, string password, string regex,out bool b)
        {
            string ip = "";
            b = true;
            bool IsTimeOut = true;
            while (IsTimeOut)
            {
                try
                {
                    HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                    httpWebRequest.Referer = ref_url;
                    httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                    httpWebRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
                    httpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727,; .NET CLR 3.0.04506,; .NET CLR 3.5.21022)";
                    httpWebRequest.Method = "GET";
                    if (string.IsNullOrEmpty(authorizationStr))
                    {
                        httpWebRequest.Credentials = new NetworkCredential(username, password);
                    }
                    else
                    {
                        httpWebRequest.Headers.Add("Authorization", authorizationStr);
                    }
                    HttpWebResponse webResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                    if (webResponse.StatusCode == HttpStatusCode.OK)
                    {
                        StreamReader sr = new StreamReader(webResponse.GetResponseStream(), Encoding.Default);

                        Regex reg = new Regex(regex);
                        string HtmlData = sr.ReadToEnd().Replace(" ", "").Replace("\n", "");
                        MatchCollection mc = reg.Matches(HtmlData);
                        if (mc.Count > 0)
                        {
                            foreach (Match mt in mc)
                            {
                                ip = mt.Groups["ip"].Value;
                            }
                        }
                        sr.Close();
                    }
                    webResponse.Close();
                    IsTimeOut = false;
                }
                catch (ThreadAbortException)
                {
                    b = false;
                }
                catch (WebException ex)
                {
                    if (ex.Status == WebExceptionStatus.ConnectFailure || ex.Status == WebExceptionStatus.Timeout)
                    {
                        Thread.Sleep(5000);
                    } 
                    else if (ex.Status == WebExceptionStatus.ProtocolError)
                    {
                        MessageBox.Show(ex.Message + "\n请检查用户名密码");
                        b = false;
                    }
                    else
                    {
                        MessageBox.Show(ex.Message);
                        b = false;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    b = false;
                }
            }

            return ip;
        }

        //通过制定网址获取IP
        private string GetIP(string url)
        {
            string ip = "";
            try
            {
                HttpWebRequest ipRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                HttpWebResponse ipResponse = (HttpWebResponse)ipRequest.GetResponse();
                if (ipResponse.StatusCode == HttpStatusCode.OK)
                {
                    StreamReader sr = new StreamReader(ipResponse.GetResponseStream(), Encoding.Default);
                    string regex = GlobalAttrib.GetIPRegex;
                    Regex reg = new Regex(regex);
                    string HtmlLine = sr.ReadLine();
                    while (HtmlLine != null)
                    {
                        HtmlLine = HtmlLine.Replace(" ", "");
                        if (reg.IsMatch(HtmlLine))
                        {
                            MatchCollection mc = reg.Matches(HtmlLine);
                            foreach (Match mt in mc)
                            {
                                ip = mt.Groups["ip"].Value;
                            }
                        }
                        HtmlLine = sr.ReadLine();
                    }
                    sr.Close();
                }
                ipResponse.Close();
            }
            catch (ThreadAbortException)
            {
            }
            catch (WebException)
            {
            }
            return ip;
        }

        #endregion
    }
}
